from OWRpy import *
import redRi18n
_ = redRi18n.get_(package = 'base')

import signals 
import redRGUI 

class confidenceInt(OWRpy): 
    globalSettingsList = ['commit']
    settingsList = []
    def __init__(self, **kwargs):
        OWRpy.__init__(self, **kwargs)
        
        #python variable
        self.data = {}
        self.RFunctionParam_X = ''
        
        #Unique R variable
        self.setRvariableNames(['confidenceInt'])
        
        #Inputs
        self.inputs.addInput("id0", "Data", signals.base.RDataFrame, self.processX)
        
        #Outputs
        self.outputs.addOutput("id0","Confidence intervals", signals.base.RDataFrame)
        
        #GUI
        area = redRGUI.base.widgetBox(self.controlArea,orientation='vertical')
        box = redRGUI.base.widgetBox(area)
        area.layout().setAlignment(box,Qt.AlignLeft)
        
        self.setAlpha=redRGUI.base.lineEdit(area, label = "Alpha", text = '0.05')
        self.isNormal = redRGUI.base.radioButtons(area,  label = "Distribution", 
        buttons = ['Normal','Undefined'], setChecked='Undefined',orientation='horizontal', callback = self.onTestChange)
        self.isVarKnown = redRGUI.base.radioButtons(area,  label = "Is population variance known?", 
        buttons = ['Yes','No'], setChecked='No',orientation='horizontal', callback = self.onTestChange)
        self.isApprox = redRGUI.base.lineEdit(area, label = "Approximative confidence interval?", text = 'Yes')
        self.isApprox.setDisabled(True)
        self.populationVar = redRGUI.base.lineEdit(self.controlArea, label = "Population variance:", text = '')
        self.populationVar.setDisabled(True)
        
        
        box.setMinimumWidth(200)
        buttonBox = redRGUI.base.widgetBox(box,orientation='horizontal')
        self.commit = redRGUI.base.commitButton(buttonBox, _("Commit"), alignment=Qt.AlignLeft, 
        callback = self.commitFunction, processOnInput=True,processOnChange=True)

    def onTestChange(self):
        if self.isNormal.getChecked() =='Normal' and self.isVarKnown.getChecked() =='Yes' :
            self.populationVar.setEnabled(True)
            self.isApprox.setText('No')
        elif self.isNormal.getChecked() =='Undefined' and self.isVarKnown.getChecked() =='Yes' :
            self.populationVar.setEnabled(True)
            self.isApprox.setText('Yes')
        elif self.isNormal.getChecked() =='Normal' and self.isVarKnown.getChecked() =='No' :
            self.populationVar.setDisabled(True)
            self.isApprox.setText('No')
        elif self.isNormal.getChecked() =='Undefined' and self.isVarKnown.getChecked() =='No' :
            self.populationVar.setDisabled(True)
            self.isApprox.setText('Yes')
            
    def processX(self, data):
        if not self.require_librarys(["compositions"]):
            self.status.setText('R Libraries Not Loaded.')
            return
        if data:
            self.RFunctionParam_X=data.getData()
            self.data = data
            self.commitFunction()
        else:
            self.RFunctionParam_X=''

    def commitFunction(self):
        if str(self.RFunctionParam_X) == '':
            self.status.setText('Data is missing.')
            return
        
        self.R('meanX<-vector()')
        self.R('sdX<-vector()')
        self.R('nX<-vector()')
        self.R('errorX<-vector()')

        self.R('populationVar<-c('+self.populationVar.text()+')')
        nCol=self.R('ncol('+str(self.RFunctionParam_X)+')')
        
        for i in range (1,self.R('ncol('+str(self.RFunctionParam_X)+')+1')):
            self.R('meanX['+str(i)+']<-mean('+str(self.RFunctionParam_X)+'[,'+str(i)+'])')
            self.R('sdX['+str(i)+']<-sd('+str(self.RFunctionParam_X)+'[,'+str(i)+'])')
            self.R('nX['+str(i)+']<-length('+str(self.RFunctionParam_X)+'[,'+str(i)+'])')        
            if self.isNormal.getChecked() =='Normal' and self.isVarKnown.getChecked() =='Yes' :
                if self.R('length(populationVar)') != nCol:
                    self.status.setText('Please enter a number of '+str(nCol)+' comma separated values in the Population variance field.')
                    return
                self.R('errorX['+str(i)+']<-qnorm(p=1-('+str(self.setAlpha.text())+')/2)*sqrt(populationVar['+str(i)+']/nX['+str(i)+'])')
            elif self.isNormal.getChecked() =='Undefined' and self.isVarKnown.getChecked() =='Yes' :
                if self.R('length(populationVar)') != nCol:
                    self.status.setText('Please enter a number of '+str(nCol)+' comma separated values in the Population variance field.')
                    return
                self.R('errorX['+str(i)+']<-qnorm(p=1-('+str(self.setAlpha.text())+')/2)*sqrt(populationVar['+str(i)+']/nX['+str(i)+'])')
            elif self.isNormal.getChecked() =='Normal' and self.isVarKnown.getChecked() =='No' :
                self.R('errorX['+str(i)+']<-qnorm(p=1-('+str(self.setAlpha.text())+')/2)*sqrt(sdX['+str(i)+']/nX['+str(i)+'])')
            elif self.isNormal.getChecked() =='Undefined' and self.isVarKnown.getChecked() =='No' :
                self.R('errorX['+str(i)+']<-qt(p=1-('+str(self.setAlpha.text())+')/2, df=nX['+str(i)+']-1)*sqrt(sdX['+str(i)+']/nX['+str(i)+'])')
        
        self.R(self.Rvariables['confidenceInt']+'<-data.frame(Error=errorX, LowerLimit=meanX-errorX, Mean=meanX, UpperLimit=meanX+errorX)')
        self.R('rownames('+self.Rvariables['confidenceInt']+')<-colnames('+str(self.RFunctionParam_X)+')')
        self.rSend("id0", signals.base.RDataFrame(self, data = self.Rvariables['confidenceInt'], checkVal = True))